package com.cheer.migrate;

import com.cheer.dao.MigrateDao;
import com.cheer.dao.OaIntegralDao;
import com.cheer.dao.OldIntegralDetailEntity;
import com.cheer.entity.OaIntegralEntity;
import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author cheer
 */
@Component
@Slf4j
public class HistoryMigrate {

    @Autowired
    private MigrateDao migrateDao;

    @Autowired
    private OaIntegralDao oaIntegralDao;

    @Autowired
    private TaskExecutor taskExecutor;

    public void migrate() {
        // 查询当前表最大id
        long maxId = migrateDao.selectMaxId();
        long tempMinId = 217589362;
        long step = 10000;
        long tempMaxId = tempMinId + step;

        do {
            Stopwatch stopwatch = Stopwatch.createStarted();
            try {
                List<OldIntegralDetailEntity> list = migrateDao.selectListInRange(tempMinId, tempMaxId);
                Iterator<OldIntegralDetailEntity> iterator = list.iterator();
                CountDownLatch countDownLatch = new CountDownLatch(list.size());

                while (iterator.hasNext()) {
                    OldIntegralDetailEntity oldEntity = iterator.next();
                    // help gc
                    iterator.remove();

                    taskExecutor.execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                if (oldEntity.getStatus() == 0 || StringUtils.isBlank(oldEntity.getType())
                                        || StringUtils.isBlank(oldEntity.getOpenid())){
                                    return;
                                }

                                OaIntegralEntity newEntity = new OaIntegralEntity()
                                        .setType(Integer.valueOf(oldEntity.getType()))
                                        .setIntegral(oldEntity.getIntegral())
                                        .setOpenid(oldEntity.getOpenid())
                                        .setAddTime(new Date(Long.valueOf(oldEntity.getAddTime())*1000));
                                if (StringUtils.isNotBlank(oldEntity.getItemsId())){
                                    newEntity.setItemsId(Integer.valueOf(oldEntity.getItemsId()));
                                }

                                oaIntegralDao.insert(newEntity);
                            } catch (Exception e) {
                                    log.error("Migration error process id = {}", oldEntity.getId());
                            } finally {
                                countDownLatch.countDown();
                            }
                        }
                    });

                }

                countDownLatch.await();
            } catch (Exception e) {
                log.error("Migration error process id = {}", tempMinId, e);
                return;
            }

            log.info("Migration process id = {} cost time = {} 秒", tempMaxId, stopwatch.elapsed(TimeUnit.SECONDS));

            tempMinId += step;
            tempMaxId += step;

        } while (tempMaxId < maxId);

        log.info("Migration success");
    }


}
